import { Provide, Inject } from '@midwayjs/decorator';
import { BaseService } from 'midwayjs-cool-core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import * as _ from 'lodash';
import { Context } from 'egg';
import { OrderEntity } from '../../entity/order';
import { PickWareHourseEntity } from '../../entity/warehouse';

/**
 * 订单号
 */
@Provide()
export class OrderService extends BaseService {
  @InjectEntityModel(OrderEntity)
  orderEntity: Repository<OrderEntity>; // 订单号
  @InjectEntityModel(PickWareHourseEntity)
  pickWareHourseEntity: Repository<PickWareHourseEntity>; // 库存

  @Inject()
  ctx: Context;
  async info(id) {
    const select =
      'SELECT a.*,b.name as pName FROM  `pick_order` `a` LEFT JOIN `pick_order` `b` ON a.pid=b.pid WHERE a.id = ' +
      id;
    const list = await this.nativeQuery(`${select}`);
    if (!list[0].pName) {
      list[0].pName = '一级分类';
    }
    return list[0];
  }
  async page() {
    const { keyWord, pid } = this.ctx.request.body;
    const where = [];
    if (keyWord) {
      where.push(`a.name LIKE '%${keyWord}%'`);
    }
    if (Number(pid) >= 0) {
      where.push(`a.pid = "${pid}"`);
    }
    const sqlWhere = where.length > 0 ? ' where ' + where.join('AND ') : '';
    const select =
      'SELECT a.*,b.name as pName FROM  `pick_order` `a` LEFT JOIN `pick_order` `b` ON `a`.`pid`=`b`.`id` ' +
      sqlWhere;
    let list = await this.nativeQuery(`${select}`);
    if (Number(pid) >= 0) {
      return {list,pagination: { page: 0, size: 0, total: 0 } }
    }
    if (list.length !== 1) {
      list = this.treeData(list,'id','pid', 'children');
      list = this.arrayTreeAddLevel(list)
    }
    return { list, pagination: { page: 0, size: 0, total: 0 } };
  }
  treeData(source, id, parentId, children) {
    const cloneData = JSON.parse(JSON.stringify(source));
    return cloneData.filter(father => {
      const branchArr = cloneData.filter(
        child => father[id] == child[parentId]
      );
      branchArr.length > 0 ? (father[children] = branchArr) : '';
      return father[parentId] == 0; // 如果第一层不是parentId=0，请自行修改
    });
  }
  // 给层级加上标识
  arrayTreeAddLevel = (array, levelName = 'level', childrenName = 'children') => {
    if (!Array.isArray(array)) return []
    const recursive = (array, level = 0) => {
        level++
        return array.map(v => {
            v[levelName] = level
            const child = v[childrenName]
            if (child && child.length) recursive(child, level)
            return v
        })
    }
    return recursive(array)
  }
  async delete(ids) {
    let idArr;
    if (ids instanceof Array) {
      idArr = ids;
    } else {
      idArr = ids.split(',');
    }
    await this.delSort(idArr);
    return ids;
  }
  async delSort(ids) {
    await this.pickWareHourseEntity
      .createQueryBuilder()
      .delete()
      .where(`orderId in (${ids})`)
      .execute();
    await this.orderEntity
      .createQueryBuilder()
      .delete()
      .where(`id in (${ids})`)
      .execute();
    return true;
  }
}
